<?php

namespace app\admin\service;

use app\common\configs\CommonData;
use app\common\model\commonModel;
use app\common\model\trAdminSession;
use app\common\model\trCache;
use app\common\model\trCoupon;
use app\common\model\trInvoices;
use app\common\model\trOrder;
use app\common\model\trSystemSet;
use app\common\model\trUser;
use app\common\util\TcScfUtil;
use app\common\util\Tools;
use think\facade\Env;

/**
 * Class Auth
 * @package app\web\service
 * 首页数据服务类
 */
class HomeService
{
    private $returnData;
    private $mall_id = 0;
    private $params;

    public function __construct($data, $params = [])
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 获取概览数据
    public function getOverviewData($adminId)
    {
        // 管理员登录信息
        $adminData = trAdminSession::getList("login_ip,create_time", ["admin_id" => $adminId], 1, 2);

        // 统计用户数据
        $userModel = new trUser();
        $userCount = $userModel->getCount(["mall_id" => $this->mall_id]);

        // 统计订单
        $orderModel = new trOrder();
        $orderCount = $orderModel->getCount(["mall_id" => $this->mall_id]);

        // 统计发票
        $invoiceModel = new trInvoices();
        $invoiceCount = $invoiceModel->getCount(["mall_id" => $this->mall_id]);

        // 待办数据
        $couponModel = new trCoupon();
        $filter = [
            ["time_from", "<=", date("Y-m-d")],
            ["time_to", "<=", date("Y-m-d", time()+86400)],
            ["mall_id", "=", $this->mall_id]
        ];
        $expireCoupon = $couponModel->getCount($filter);
        $handleData[] = ["text" => "{$expireCoupon}张优惠券即将到期", "url" => "/coupon/list"];
        $invoiceModel = new trInvoices();
        $handleInvoice = $invoiceModel->getCount(["status" => 1, "mall_id" => $this->mall_id]);
        $handleData[] = ["text" => "{$handleInvoice}张发票申请待处理", "url" => "/invoice/list"];
        $airportCount = $orderModel->getCount(["type" => 1, "status" => 4, "mall_id" => $this->mall_id]);
        $handleData[] = ["text" => "{$airportCount}个机场接送订单未分配", "url" => "/order/list?status=4&type=1"];
        $carCount = $orderModel->getCount(["type" => 3, "status" => 4, "mall_id" => $this->mall_id]);
        $handleData[] = ["text" => "{$carCount}个跨境专车接送订单未分配", "url" => "/order/list?status=4&type=3"];

        $result = $this->checkUseNormal(); // 检查是否可以正常使用或者欠费

        $wxAppVersion = commonModel::getList(wxAppUpgradeTable, "version", ["mall_id" => $this->mall_id], 1, 1, "create_time desc", false);
        if(empty($wxAppVersion)){
            $wxAppVersion = [["version" => "0.0.0"]];
        }
        $wxAppUpdateStatus = false;
        $checkWxAppUpdateRes = Tools::curl(CommonData::WX_MINI_PUBLISH_SERVER_URL.CommonData::$wxMiniPublishRoute['checkUpdate'], json_encode([
            "version" => $wxAppVersion[0]["version"], "projectName" => CommonData::PROJECT_NAME
        ], JSON_UNESCAPED_UNICODE));
        $checkWxAppUpdateRes = json_decode(trim($checkWxAppUpdateRes, chr(239) . chr(187) . chr(191)), true);
        if(isset($checkWxAppUpdateRes["code"]) && $checkWxAppUpdateRes["status"] == "1"){
            $wxAppUpdateStatus = true;
        }
        $this->returnData["data"] = [
            "managerData" => empty($adminData) ? "" : (isset($adminData[1]) ? $adminData[1] : $adminData[0]), "userCount" => $userCount, "orderCount" => $orderCount,
            "invoiceCount" => $invoiceCount, "handleData" => $handleData, "tcAccountInfo" => $result, "systemData" => [
                "wxAppVersion" => "v".$wxAppVersion[0]["version"], "mallVersion" => "v".CommonData::VERSION, "wxAppUpdateStatus" => $wxAppUpdateStatus
            ]
        ];
        return $this->returnData;
    }

    public function getStatisticsData()
    {
        list($y, $m, $d) = explode('-', date('Y-m-d'));
        $todayTime = mktime(0, 0, 0, $m, $d, $y);
        $orderModel = new trOrder();

        // 总订单
        $orderCount = $orderModel->getCount([["create_time", "<=", $todayTime], ["mall_id", "=", $this->mall_id]]);

        // 已付款 '订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款',
        $payOrderCount = $orderModel->getCount([["create_time", "<=", $todayTime], ["status", "not in", "1,3,9,11"], ["mall_id", "=", $this->mall_id]]);  // 已付款数，去除待支付、已取消、已退款、部分退款

        // 订单总额
        $moneyData = $orderModel->getFields("SUM(`pay_money`) AS `money`", [["create_time", "<=", $todayTime], ["status", "<>", "3,9,11"], ["mall_id", "=", $this->mall_id]], true, false);  // 订单总额，去除已退款、部分退款
        $orderAmount = $moneyData["money"];

        // 7日内的订单指标
        $time = mktime(0, 0, 0, $m, $d - 7, $y);
        $res = $this->getOrderChartByTime($time, $todayTime);
        $chartData[] = ["title" => "7日订单指标", "data" => $res["chart"], "list" => $res["list"]];

        // 15日内的订单指标
        $time = mktime(0, 0, 0, $m, $d - 15, $y);
        $res = $this->getOrderChartByTime($time, $todayTime);
        $chartData[] = ["title" => "15日订单指标", "data" => $res["chart"], "list" => $res["list"]];

        // 30日内的订单指标
        $time = mktime(0, 0, 0, $m, $d - 30, $y);
        $res = $this->getOrderChartByTime($time, $todayTime);
        $chartData[] = ["title" => "30日订单指标", "data" => $res["chart"], "list" => $res["list"]];

        $this->returnData["data"] = [
            "orderCount" => $orderCount, "payOrderCount" => $payOrderCount, "orderAmount" => $orderAmount,
            "chartData" => $chartData
        ];
        return $this->returnData;
    }

    public function getSearchOrderList(){
        if (empty($this->params['startTime']) || empty($this->params['endTime'])) { // 默认是当月开始时间到今天
            list($y, $m, $d) = explode('-', date('Y-m-d'));
            $start = mktime(0, 0, 0, $m, 1, $y);
            $end = mktime(23, 59, 59, $m, $d, $y);
        }else {
            list($y, $m, $d) = explode('-', $this->params['startTime']);
            $start = mktime(0, 0, 0, $m, $d, $y); // 开始时间戳
            list($y, $m, $d) = explode('-', $this->params['endTime']);
            $end = mktime(23, 59, 59, $m, $d, $y); // 结束时间戳
        }
        $count = ceil(($end - $start) / 86400); // 总条数
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        $end = $end - (86400 * ($page - 1)*$pageSize); // 从第几页开始
        $i = 0; // 计数
        $orderList = [];
        do{
            $res = $this->getOrderListByTime($end - 86399, $end); // 跟统计保持一致 ，  mktime(23, 59, 59, $m, $i, $y); 是今晚凌晨前1秒
            $res["time"] = date("Y-m-d", $end);
            $orderList[] = $res;
            $end = $end - 86400;
            if($i++ && $i >= $pageSize){
                break;
            }
        }while($end >= $start);
        if(!$orderList){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $orderList, 'totalPage' => ceil($count/$pageSize), 'currentPage' => $page, 'count' => $count];
        }
        return $this->returnData;
    }

    // 统计订单时间范围内的数据
    public function getOrderChartByTime($start, $end)
    {
        $orderModel = new trOrder();
        $orderData = $orderModel->getFields("status,pay_money", [["create_time", "<=", $end], ["create_time", ">=", $start], ["mall_id", "=", $this->mall_id]], false, false);  // 订单统计
        $count = $pay = $noPay = $trash = $money = 0;
        foreach ($orderData as $item) {
            $item = Tools::transferFields($item->getData());
            // 订单状态：订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款
            switch ($item["status"]) {
                case "1":
                    $noPay++;
                    break;
                case "2":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "10":
                    $pay++;
                    break;
                case "3":
                case "9":
                case "11":
                    $trash++;
                    break;
            }
            $money = $money + $item["payMoney"];
            $count++;  //总数
        }
        return [
            "chart" => [
                ["value" => $pay, "name" => "已付款"],
                ["value" => $noPay, "name" => "待付款"],
                ["value" => $trash, "name" => "作废"],
            ],
            "list" => [
                "orderCount" => $count,
                "orderAmount" => number_format($money, 2, '.', ''),
            ]
        ];
    }

    // 统计订单时间范围内的数据
    public function getOrderListByTime($start, $end)
    {
        $orderModel = new trOrder();
        $orderData = $orderModel->getFields("status,pay_money", [["create_time", "<=", $end], ["create_time", ">=", $start], ["mall_id", "=", $this->mall_id]], false, false);  // 订单统计
        $count = $pay = $noPay = $complete = $money = 0;
        foreach ($orderData as $item) {
            $item = Tools::transferFields($item->getData());
            $money = $money + $item["payMoney"];
            $count++;  //总数
            // 订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款
            if($item["status"] == "1"){
                $noPay++;
            }elseif(in_array($item["status"], [2,4,5,6,7,8,10])){
                $pay++;
            }
            if($item["status"] == "8"){
                $complete++;
            }
        }
        return [
            "totalCount" => $count,
            "completeCount" => $complete,
            "payCount" => $pay,
            "noPayCount" => $noPay,
            "money" => number_format($money, 2, '.', ''),
        ];
    }

    public function getWxAppCloudDevelop(){
        $url = "https://service-emhatyrq-1251017581.gz.apigw.tencentcs.com/test/api/cf/request"; // 默认租车的nodejs包的接口地址
        if(is_file(Env::get("root_path") . "/wsConfig.json")){
            $config = json_decode(file_get_contents(Env::get("root_path") . "/wsConfig.json"), 1);
            if(!empty($config["cloud"]["list"][1]["name"])) {
                $url = substr(request()->domain(), 0, strrpos(request()->domain(), "/")) . "/" . $config["cloud"]["list"][1]["name"] . "/api/cf/request";
            }
        }
        $res = Tools::getFormData($this->params);
        $result = Tools::curl($url, $res[0], ['Content-Type: multipart/form-data; boundary=' . $res[1]]);
        $result = json_decode($result, true);
        if ($result) {
            $this->returnData["code"] = $result["code"];
            $this->returnData["msg"] = $result["errMsg"];
            unset($result["code"], $result["errMsg"]);
            $this->returnData = array_merge($this->returnData, $result);
        }
        return $this->returnData;
    }

    // 获取腾讯云账号余额
    public function checkUseNormal(){
        $tcConfig = trSystemSet::getValue("tcConfig");
        if(empty($tcConfig["secretId"]) && empty($tcConfig["secretKey"])){
            return [];
        }
        $scf = new TcScfUtil($tcConfig["secretId"], $tcConfig["secretKey"]);
        $res = $scf->describeAccountBalance(); // 余额
        if($res["code"] == "0"){
            return ["balance" => $res["data"]["Balance"] / 100, "result" => "获取成功"];
        }else{
            return ["balance" => 0, "result" => $res["msg"]];
        }
    }

    public function getJavaScriptStatus(){
        $data = [];
        request()->mallData = ["id" => 0]; // 重置商城ID
        foreach (CommonData::$javascriptList as $key => $value){
            $cacheData = trCache::getValue("value", ["key" => $key]);
            if(!empty($cacheData) && is_array($cacheData)){
                if($cacheData['execTime'] >= date("Y-m-d 00:00:00") && $cacheData['execTime'] <= date("Y-m-d 23:59:59")){
                    $cacheData["status"] = 1;
                    $cacheData["statusText"] = "正常";
                }else{
                    $cacheData["status"] = 0;
                    $cacheData["statusText"] = "异常";
                }
                $data[] = $cacheData;
            }
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }
}